import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_demo/components/Toast.dart';
import 'package:flutter_demo/store/store.dart';
import 'package:flutter_demo/utils/LocalStorage.dart';

enum HttpMethod { Get, Post, Put, Delete }

class Api {
  // 请求封装
  static Future<dynamic> request(String url,
      {String txCode: '',
      Map<String, dynamic> header,
      HttpMethod method: HttpMethod.Get,
      Map<String, dynamic> bodys,
      context}) async {
    var params = new Map<String, dynamic>.from(bodys);
    Map<String, dynamic> headers = {};

    Store store = Store();
    if (header ?? false) {
      headers = new Map<String, dynamic>.from(header);
    }
    var user;
    String platform;
    if (Platform.isAndroid) {
      platform = "android";
    } else if (Platform.isIOS) {
      platform = "ios";
    }
    headers['platform'] = platform;
    // 判断是否登录
    bool isHasKey = await LocalStorage.containsKey('user');
    if (isHasKey) {
      user = LocalStorage.getStorage('user');
      headers['Authorization'] = 'Bearer ${user['token']}';
    }
    Dio dio = new Dio();
    print(params);
    BaseOptions options = BaseOptions(headers: headers);
    options.connectTimeout = 10 * 1000;
    options.receiveTimeout = 20 * 1000;
    dio.options = options;
    var stringUrl = store.baseUrl + url + txCode;
    Response response;

    switch (method) {
      case HttpMethod.Get:
        {
          response = await dio.get(stringUrl, queryParameters: params);
        }
        break;
      case HttpMethod.Post:
        {
          response = await dio.post(stringUrl, data: params);
        }
        break;
      case HttpMethod.Put:
        {
          response = await dio.put(stringUrl, data: params);
        }
        break;
      case HttpMethod.Delete:
        {
          response = await dio.delete(stringUrl, data: params);
        }
        break;
    }
    if (response.statusCode == 200) {
      if (response.data['code'] != 200) {
        Toast.toast(context, msg: response.data['message']);
      }
      return response.data;
    } else {
      return response.data;
    }
  }
}
